package controller;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import dto.Protocol;
import dto.ResponseDto;
import dto.StatusDto;
import jms.Sender;
import pojo.Merchant;
import service.FileUploadService;
import service.MerchantService;
import util.FileUtil;
import util.HttpUtil;
import util.JsonUtil;

@Controller
@Configuration
@PropertySource("classpath:default.properties")
public class MerchantController {
	
	
    @Resource(name = "merchantServiceImpl")
    private MerchantService merchantService;
    @Resource(name="jmsSender")
    private Sender sender;
    @Resource
    Environment env;
    @Resource(name="fileUploadService")
    private FileUploadService uploadService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(Merchant merchant, MultipartFile idCard, MultipartFile avatar, Model model) {
        String savePath = env.getProperty("image.savePath");
        System.out.println(avatar.getOriginalFilename());
        String[] names = avatar.getOriginalFilename().split("\\.");
        String suffix = names[names.length-1];
        String avatarKey = savePath+"avatar/"+UUID.randomUUID().toString()+"."+suffix;
        merchant.setAvatarPath(avatarKey); 
        ResponseDto avatarResponse;
		try {
			avatarResponse = uploadService.upload(env.getProperty("image.server"),avatar.getInputStream(), avatarKey);
			 if (avatarResponse.getCode()!=1) {
					model.addAttribute("error", "error happen");
					return "register";
				}
		     String[] idNames = avatar.getOriginalFilename().split("\\.");
		     String idSuffix = names[idNames.length-1];
		     String idKey = savePath+"idCard/"+UUID.randomUUID().toString()+"."+idSuffix;
		     merchant.setIdCardPath(idKey);
		        
		     ResponseDto idCardResponse= uploadService.upload(env.getProperty("image.server"),idCard.getInputStream(), idKey);
		     if (idCardResponse==null||idCardResponse.getCode()!=1) {
		    	 model.addAttribute("error", "error happen");
				return "register";
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
        try {
        	Protocol sendProtocol = new Protocol(merchant.getName(), merchant.getAddress(), merchant.getIdCardPath(), merchant.getAvatarPath(), Protocol.REGISTER);
        	sender.send(JsonUtil.toJsonString(sendProtocol));
        	merchantService.register(merchant);
		} catch (Exception e) {
			model.addAttribute("error", "账号名已被使用，请更换");
			return "register";
		}
        return "login";
       
    }
    
    @RequestMapping(value = "/reRegister", method = RequestMethod.POST)
    public String reRegister(Merchant merchant, MultipartFile idCard, MultipartFile avatar, HttpServletRequest request,Model model) {
        String savePath = env.getProperty("savePath");
        ServletContext context = request.getServletContext();
        String base64IdCard = "";
        String base64Avatar = "";
        String idCardPath = "";
        String avatarPath = "";
    //    String realPath = context.getRealPath("/");
        String upLoadPath = "";

        avatarPath = new Date().getTime() + avatar.getOriginalFilename();
        merchant.setAvatarPath(avatarPath);
        upLoadPath = savePath + "/" + avatarPath;
        try {
            base64Avatar = FileUtil.upload(avatar.getInputStream(), upLoadPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        idCardPath = new Date().getTime() + idCard.getName();
        merchant.setIdCardPath(idCardPath);
        upLoadPath = savePath + "/" + idCardPath;
        try {
            base64IdCard = FileUtil.upload(idCard.getInputStream(), upLoadPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
        	merchantService.update(merchant);
		} catch (Exception e) {
			model.addAttribute("error", "账号名已被使用，请更换");
			return "reRegister";
		}
        return "../login";
       
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(Merchant merchant,Model model) {
        System.out.println(merchant.getName());
        System.out.println(merchant.getName());
        try {
        	merchantService.login(merchant);
        } catch (Exception e) {
			model.addAttribute("error", "账号或密码错误");
			return "login";
		}
        return "showFoodList";
    }
    
    @ResponseBody
    @RequestMapping(value = "getStatue", method = RequestMethod.POST)
    public StatusDto getStatue(HttpServletRequest request) {
	
		Merchant merchant = (Merchant) request.getSession().getAttribute("user");

		String name = merchant.getName();
        String status = null;
        StatusDto statusDto = new StatusDto();
        try {
        	status = HttpUtil.getResponseStr("/admins/m/status/get?name=" + name);
		} catch (Exception e) {
			statusDto.setStatus("out");
			return statusDto;
		}
        return statusDto;
	}
}
